package impl

import (
	"context"

	"gitee.com/go-course/go9/projects/devcloud/mcenter/apps/policy"
	"gitee.com/go-course/go9/projects/devcloud/mcenter/apps/role"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 创建策略
func (i *impl) CreatePolicy(ctx context.Context, in *policy.CreatePolicyRequest) (
	*policy.Policy, error) {
	ins := policy.New(in)

	_, err := i.col.InsertOne(ctx, ins)
	if err != nil {
		return nil, err
	}

	return ins, nil
}

// 查询策略
func (i *impl) QueryPolicy(ctx context.Context, in *policy.QueryPolicyRequest) (
	*policy.PolicySet, error) {
	set := policy.NewPolicySet()

	// 构造查询条件
	filter := bson.M{}

	if in.UserId != "" {
		filter["user_id"] = in.UserId
	}
	if in.Namespace != "" {
		filter["namespace"] = in.Namespace
	}

	opts := &options.FindOptions{}
	opts.SetLimit(int64(in.Page.PageSize))
	opts.SetSkip(in.Page.ComputeOffset())

	cursor, err := i.col.Find(ctx, filter, opts)
	if err != nil {
		return nil, err
	}

	// 执行查询SQL
	for cursor.Next(ctx) {
		ins := policy.NewDefaultPolicy()
		if err := cursor.Decode(ins); err != nil {
			return nil, err
		}
		set.Add(ins)
	}

	// mysql : Join, 导致你和另外一个模块强耦合
	// mongo: xxx
	if in.WithRole {
		req := role.NewQueryRoleRequest()
		// Go 可变参数
		req.AddRoleId(set.RoleIds()...)
		req.Page.PageSize = set.Len()
		rs, err := i.role.QueryRole(ctx, req)
		if err != nil {
			return nil, err
		}
		// 遍历角色列表
		for i := range rs.Items {
			r := rs.Items[i]
			set.SetRole(r)
		}
	}

	// 统计总数
	set.Total, err = i.col.CountDocuments(ctx, filter)
	if err != nil {
		return nil, err
	}
	return set, nil
}
